<?php
// 预设密码
$passwords = ['chuangmeng', 'keke', '2076659780'];

// 判断请求是否为POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 获取POST数据
    $device = $_POST['device'];
    $state = $_POST['state'];
    $password = isset($_POST['password']) ? $_POST['password'] : '';

    // 检查密码是否正确（可以为空）
    if (!in_array($password, $passwords) && $password !== '') {
        echo json_encode(['success' => false, 'message' => '密码错误']);
        exit;
    }

    // 根据设备设置API URL和秘钥
    if ($device === 'door') {
        $url = "https://pt.feiyangkeji.com/api/device/setstate/csDPzkZqTYrFKtfW/CZTBaxWqDw001";
    } elseif ($device === 'light') {
        $url = "https://pt.feiyangkeji.com/api/device/setstate/csDPzkZqTYrFKtfW/CZEQVPURjS001";
    } else {
        echo json_encode(['success' => false, 'message' => '设备不支持']);
        exit;
    }

    // 设置请求参数
    $data = http_build_query(['state' => $state]);

    // 发送POST请求
    $options = [
        'http' => [
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => $data,
        ],
    ];
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    if ($result === FALSE) {
        echo json_encode(['success' => false, 'message' => '操作失败']);
    } else {
        echo json_encode(['success' => true]);
    }
} else {
    echo json_encode(['success' => false, 'message' => '无效请求']);
}
?>
